package com.yunduansing.demo.config;

import com.yunduansing.demo.model.common.CacheKeyPrefix;
import com.yunduansing.demo.service.impl.AuthUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenClearLogoutHandler implements LogoutHandler {

    private AuthUserService jwtUserService;
    @Autowired
    private RedisTemplate redisTemplate;

    public TokenClearLogoutHandler(AuthUserService jwtUserService) {
        this.jwtUserService = jwtUserService;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        clearToken(authentication);
    }

    protected void clearToken(Authentication authentication) {
        if(authentication == null)
            return;
        UserDetails user = (UserDetails)authentication.getPrincipal();
        if(user!=null && user.getUsername()!=null){
            jwtUserService.deleteUserLoginInfo(user.getUsername());
            //移除登录的缓存
            redisTemplate.delete(CacheKeyPrefix.LOGIN_USER+user.getUsername());
        }
    }

}
